package com.pzy.excel;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.junit.jupiter.api.Test;

import cn.idev.excel.FastExcel;
import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.read.listener.ReadListener;
import lombok.Getter;

public class FastExcelTest01 {

    /**
     * 写入测试
     */
    @Test
    public void writeExcel01() {
        String fileName = "simpleWriteDemo.xlsx";
        this.writeExcelTemplate(fileName);
    }

    private void writeExcelTemplate(String fileName) {

        // 2. Prepare your data
        List<Product> dataList = new ArrayList<>();
        dataList.add(Product.builder().type(1).name("联想 Thinkbook").price(BigDecimal.valueOf(9999.994))
                .createDate(new Date())
                .prototypeAndColor(PrototypeAndColor.builder().prototype("I7").color("红色").build()).build());
        dataList.add(Product.builder().type(2).name("书包").price(BigDecimal.valueOf(108.145)).createDate(new Date())
                .build());
        FastExcel.write(fileName, Product.class)
                .sheet("商品") // Optionally specify sheet name
                .doWrite(dataList);
    }

    @Test
    public void testRead01() {
        String fileName = "simpleWriteDemo.xlsx";
        this.writeExcelTemplate(fileName);

        DemoDataListener dataListener = new DemoDataListener();
        FastExcel.read(fileName, Product.class, dataListener).sheet().doRead();

        System.out.println(dataListener.getDataList());
    }
}

@Getter
class DemoDataListener implements ReadListener<Product> {

    private List<Product> dataList = new ArrayList<>();

    @Override
    public void invoke(Product data, AnalysisContext context) {
        this.dataList.add(data);
        System.out.println(String.format("[%s]解析一行记录", Thread.currentThread().getName()));
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        System.out.print(String.format("[%s] 所有数据解析完毕", Thread.currentThread().getName()));
    }

}
